extends Node2D

## 门的激活方向
enum DIRECTION {LEFT, RIGHT, TOP, BOTTOM}

@export var activeDirection = DIRECTION.RIGHT		## 有效激活方向

# 地图模板
@onready var roomSources = [
	load("res://Room/tscn/GrassRoom.tscn"),
	load("res://Room/tscn/StoneRoom.tscn")
]

@onready var area = $Area2D
@onready var util = Util.new()
@onready var mapConfig = util.findOne("$[MinMap]", util.findOne("$[CanvasLayer]", util.findOne("!", self))).mapConfig
static var currentRoomPosition = Vector2.ZERO
# 记录生成的房间坐标, 默认保存初始坐标
static var minMap = null

func _ready():
	area.connect("body_entered", playerEnter)
	# 只初始化一次小地图
	if minMap == null:
		minMap = util.findOne("$[MinMap]", util.findOne("![CanvasLayer]", self))


func playerEnter(body):
	# 寻找摄像机
	var camera = util.findOne("![Camera2D]", self)
	# 触发方向, 控制摄像机位置
	match activeDirection:
		DIRECTION.LEFT:
			# 左激活
			if body.global_position.x < self.global_position.x && body.direction.x > 0 && body.direction.y == 0:
				camera.global_position.x += 480
				currentRoomPosition.x += 480
				# 因为房间是由墙隔开的, 这个门的作用就是将玩家传送到另一个房间坐标
				body.global_position.x += 110
				# 生成房间
				createRoom(currentRoomPosition)
		
		DIRECTION.RIGHT:
			# 右激活
			if body.global_position.x > self.global_position.x && body.direction.x < 0 && body.direction.y == 0:
				camera.global_position.x -= 480
				currentRoomPosition.x -= 480
				body.global_position.x -= 110
				createRoom(currentRoomPosition)
			
		DIRECTION.TOP:
			if body.global_position.y < self.global_position.y && body.direction.y > 0 && body.direction.x == 0:
				camera.global_position.y += 272
				currentRoomPosition.y += 272
				body.global_position.y += 110
				createRoom(currentRoomPosition)
			
		DIRECTION.BOTTOM:
			if body.global_position.y > self.global_position.y && body.direction.y < 0 && body.direction.x == 0:
				camera.global_position.y -= 272
				currentRoomPosition.y -= 272
				body.global_position.y -= 110
				createRoom(currentRoomPosition)
				
				
'''
	创建房间
	@param position 房间位置
'''
func createRoom(position):
	for item in minMap.existRoom:
		if item == position:
			# 更新玩家在小地图的位置
			minMap.update_minimap(position)
			print("房间已存在")
			return
	
	print("生成新房间")
	# 将新坐标放入地图
	minMap.existRoom.append(position)
	# 当地图没有生成过才进行生成		
	# 获得世界
	var rootNode = util.findOne("$[Rooms]", get_tree().root.get_child(0))
	
	# 设置房间位置
	# 寻找对应的房间配置
	for item in mapConfig:
		# 如果配置文件中有房间坐标和摄像机坐标一样, 那么就生成这个配置的房间
		if (item["position"]) == position:
			var roomNode = item["source"].instantiate()
			# 房间的位置
			roomNode.position = position
			# 房间的类型
			roomNode.roomType = item["type"]
			# 门的配置
			roomNode.enableDoor = item["door"]
			# 加入地图
			rootNode.add_child(roomNode)
			# 更新小地图玩家当前位置
			minMap.update_minimap(position)
			break
	
